package com.student_exam_system.Filter;

import com.student_exam_system.Util.JwtUtil;
import com.student_exam_system.pojo.PaperClass;
import com.student_exam_system.service.PaperClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;

public class TimeInterceptor implements HandlerInterceptor {

    @Autowired
    @Qualifier("paperClassServiceImpl")
    private PaperClassService paperClassService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        int jwtUserId = JwtUtil.getJWTUserId(token);
        int paperId = Integer.parseInt(request.getParameter("paperId"));
        PaperClass paperClass = paperClassService.queryPaperClassByUserIdAndPaperId(paperId, jwtUserId);
        Timestamp endExam = new Timestamp(paperClass.getPcTime().getTime() + paperClass.getPcExamTime() * 60L);
        boolean flag = System.currentTimeMillis()>=paperClass.getPcTime().getTime()&&
                System.currentTimeMillis()<= endExam.getTime();

        if (flag){
            request.getSession().setAttribute("examStart",paperClass.getPcTime());
            request.getSession().setAttribute("examEnd",endExam);
            return true;
        }
        else {
            throw new RuntimeException("不在指定考试时间的范围内");
        }
    }
}
